package com.example.demoribbonclientwithouteureka;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class MyRibbonClient {
    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    LoadBalancerClient ribbonLoadBalancerClient;

    @Autowired
    @LoadBalanced
    RestTemplate restTemplate;

    //从Eureka中根据服务名称选择第一一个可用服务
    @RequestMapping(value="/ulogin1",produces = "application/json;charset=UTF-8")
    public Map userlogin1() {
//        List<ServiceInstance> list = discoveryClient.getInstances ("userlogin");
//        ServiceInstance serviceInstance=list.get(0);

       // 启用负载均衡
        ServiceInstance serviceInstance=ribbonLoadBalancerClient.choose("USERLOGIN");

        String serviceUrl = serviceInstance.getUri().toString();
        System.out.println(serviceUrl);
        RestTemplate restTemplate = new RestTemplate();
        logger.info("ribbon 负载均衡");
        return restTemplate.getForObject(serviceUrl + "/login", Map.class);
    }

    //启用ribbon负载均衡策略
    @RequestMapping(value="/ulogin2",produces = "application/json;charset=UTF-8")
    public Map userlogin2() {

        logger.info("ribbon 负载均衡简化版");
        return restTemplate.getForObject("http://USERLOGIN/login", Map.class);
    }
}

